<?php
/**
 * Created by lzl
 * Date: 2021 2021/11/2
 * Time: 11:25
 */
namespace App\Forms;


use App\Models\Order;
use App\Models\OrderDetail;
use Illuminate\Database\Query\Builder;

class OrderForms extends BaseForm
{

    /**
     * @param $order
     * @return Order|\Illuminate\Database\Eloquent\Model
     */
    public function createOrder($order)
    {
        return Order::create($order);
    }


    /**
     * @param $order
     * @return OrderDetail|\Illuminate\Database\Eloquent\Model
     */
    public function createOrderDetail($order)
    {
        return OrderDetail::create($order);
    }


    public function getUserOrderCount($uid)
    {
        $order = Order::where('uid', $uid)
            ->groupBy('status')
            ->select(['status', \DB::raw('count(*) as count')])
            ->get()
            ->pluck('count','status');

        return $order;
    }


    /**
     * 订单列表
     * @param $validated
     * @return mixed
     */
    public function getOrderList($validated)
    {


        $list = Order::where(function($q) use ($validated){
            /**
             * @var Builder $q
             */
            if(isset($validated['status']) && $validated['status']){
                $q->where('status', $validated['status']);
            }

            if(isset($validated['uid']) && $validated['uid'] ){
                $q->where('uid', $validated['uid']);
            }

            if(isset($validated['order_sn']) && $validated['order_sn'] ){
                $q->where('order_sn', $validated['order_sn']);
            }

            return $q;
        })->page(function($q) use ($validated){

            if(isset($validated['page']) && isset($validated['limit'])){
                $q->page($validated['page'], $validated['limit']);
            }

            return $q;
        })->orderBy('id','desc')->get()->toArray();

        if(count($list)){
            foreach ($list as &$item) {
                $item['details'] = OrderDetail::where('order_id', $item['id'])->get();
            }
        }
        
        return $list;
    }


    /**
     * 订单详情
     * @param $oid
     * @param array $field
     * @return Order|mixed
     */
    public function getOrderDetail($oid, $field = ["*"])
    {
        return Order::find($oid, $field);
    }

    /**
     * @param $oid
     * @param array $field
     * @return \Illuminate\Support\Collection
     */
    public function orderDetailList($oid, $field = ["*"])
    {
        return OrderDetail::where('order_id', $oid)->get($field);
    }


    /**
     * @param $oid
     * @param array $update
     * @return bool|int
     */
    public function updateOrder($oid, $update = [])
    {
        return Order::whereKey($oid)->update($update);
    }
}